﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Model;
using Helper;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using System.Threading;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework;

namespace DBFM7
{
    /// <summary>
    /// copyright:kklldog
    /// date:2011-08-29
    ///  qq:17014842
    /// </summary>
    public partial class MainPage : PhoneApplicationPage
    {
        private ChannelType _CurrentChannel=ChannelType.None;
        private bool IsUserPaused = false;
        private DispatcherTimer _timer = new DispatcherTimer();
        private dbSong CurrentSong
        {
            get {
                if (PlayListHelper.pl.song.Count <= PlayListHelper.SongIndex)
                    return null;
                return PlayListHelper.pl.song[PlayListHelper.SongIndex]; 
            }
        }
        private SlideTransition st = null;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            
            PlayListHelper.ReFreshComplete += new Action(PlayListHelper_ReFreshComplete);
            MediaPlayer.MediaStateChanged+=new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);
            _timer.Interval = TimeSpan.FromMilliseconds(500);
            _timer.Tick += new EventHandler(_timer_Tick);
            
            AlubmImage.ImageOpened += new EventHandler<RoutedEventArgs>(AlubmImage_ImageOpened);
            btn_f = this.ApplicationBar.Buttons[0] as ApplicationBarIconButton;
            btn_p = this.ApplicationBar.Buttons[1] as ApplicationBarIconButton;
            btn_n = this.ApplicationBar.Buttons[2] as ApplicationBarIconButton;
            //channelNav.SelectChanged += new Action<ChannelType>(channelNav_SelectChanged);
            channelNav.BackToChannelNav += new Action(channelNav_BackToChannelNav);
           
        }

        void channelNav_BackToChannelNav()
        {
            TranToChannelTile();
          
        }


        void MediaPlayer_MediaStateChanged(object sender, EventArgs e)
        {
            if (MediaPlayer.State == MediaState.Paused)
            {
                if (!this.IsUserPaused)
                {
                    this.btn_n_Click(sender, e);
                }
               
            }
        }


        void AlubmImage_ImageOpened(object sender, RoutedEventArgs e)
        {
            this.AlubmImage.Opacity = 1;
            this.AlubmImage_Copy.Opacity = 0.3;
            this.Tran();
        }

        void PlayListHelper_ReFreshComplete()
        {
           // this.AppBar.IsVisible = true;
            this.Play(CurrentSong);
            ChangeBtnImg(this.btn_p,"pause");
        }

        void _timer_Tick(object sender, EventArgs e)
        {
            if (MediaPlayer.State == MediaState.Playing)
            {
                this.PlayTime.Text = string.Format("{0:00}:{1:00}", MediaPlayer.PlayPosition.Minutes, MediaPlayer.PlayPosition.Seconds);
            }
            if (MediaPlayer.State == MediaState.Stopped)
            {
                this.PlayTime.Text = "";
                _timer.Stop();
            }
        }


        private void ChangeBtnImg(ApplicationBarIconButton btn, string type)
        {
            string url_play = "/ICON/appbar.transport.play.rest.png";
            string url_pause = "/ICON/appbar.transport.pause.rest.png";
            string url_fav = "/ICON/appbar.favs.rest.png";
            string url_fav_addto = "/ICON/appbar.favs.addto.rest.png";
            if (type == "play")
            {
                btn.IconUri = new Uri(url_play, UriKind.RelativeOrAbsolute);
                btn.Text = "播放";
            }
            else if (type == "pause")
            {
                btn.IconUri = new Uri(url_pause, UriKind.RelativeOrAbsolute);
                btn.Text = "暂停";
            }
            else if (type == "fav")
            {
                btn.IconUri = new Uri(url_fav, UriKind.RelativeOrAbsolute);
                btn.Text = "最爱";
            }
            else if (type == "fav_addto")
            {
                btn.IconUri = new Uri(url_fav_addto, UriKind.RelativeOrAbsolute);
                btn.Text = "收藏";
            }
        }


        private void Play(dbSong song)
        {
            MediaPlayer.Stop();
            if (song == null)
            {
                this.SongName.Text = "No Song！";
                this.AlubmImage.Source = null;
                this.AlubmImage_Copy.Source = null;
                return;
            }
            if (DbHelper.IsFavSong(song))
            {
                this.ChangeBtnImg(this.btn_f, "fav");
            }
            else
            {
                this.ChangeBtnImg(this.btn_f, "fav_addto");
            }
            Song s = Song.FromUri(song.title, new Uri(song.url));
            MediaPlayer.Play(s);
            DbHelper.DelSong(song);
            this.SongName.Text = song.artist+"-"+ song.title;
            this.SongNameMarquee();
            this.AlubmImage.Source = new BitmapImage(new Uri(song.picture,UriKind.Absolute));
            this.AlubmImage_Copy.Source = this.AlubmImage.Source;
            this.AlubmImage.Opacity = 0;
            this.AlubmImage_Copy.Opacity = 0;

            _timer.Start();
        }
        /// <summary>
        /// 歌曲名称滚动
        /// </summary>
        private void SongNameMarquee()
        {
            this.sb.Stop();
            double sysWidth = System.Windows.Application.Current.Host.Content.ActualWidth;//屏幕宽度
            if (sysWidth <= this.SongName.ActualWidth)
            {
                animation.From = sysWidth;
                animation.To = -this.SongName.ActualWidth - (sysWidth - 360) / 2;//360为Canvas宽度
                this.sb.Begin();
            }
            else
            {//canvas居中
                this.SongName.SetValue(Canvas.LeftProperty, 180-this.SongName.ActualWidth/2);
            }

        }
        /// <summary>
        /// 专辑画出效果
        /// </summary>
        private void Tran()
        {
            if (st == null)
            {
                st = new SlideTransition();
            }
            st.Mode = SlideTransitionMode.SlideLeftFadeIn;
            ITransition transition = st.GetTransition(this.AlubmImage_Double);
            transition.Completed += delegate
            {
                transition.Stop();
            };
            transition.Begin();
        }

   

        private TurnstileTransition tt;
        ITransition transitionToChannelTile;
        private void TranToChannelTile()
        {
            if (tt == null)
            {
                tt = new TurnstileTransition();
            }
            tt.Mode = TurnstileTransitionMode.BackwardOut;
            
            transitionToChannelTile = tt.GetTransition(this.LayoutRoot);
            transitionToChannelTile.Completed += new EventHandler(transition_Completed);
            transitionToChannelTile.Begin();
        }
        void transition_Completed(object sender, EventArgs e)
        {
            this.Visibility = Visibility.Collapsed;
            transitionToChannelTile.Stop();
            this.NavigationService.Navigate(new Uri("/ChannelTile.xaml", UriKind.Relative));
        }

        private  ChannelType GetChannelType(string channel)
        {
            ChannelType ct = (ChannelType)Enum.Parse(typeof(ChannelType), channel, false);
            return ct;
        }


        private void btn_p_Click(object sender, EventArgs e)
        {
            if ( MediaPlayer.State==MediaState.Stopped)
            {
                this.Play(CurrentSong);
                this.IsUserPaused = false;
                ChangeBtnImg(this.btn_p,"pause");
            }
            else if ( MediaPlayer.State==MediaState.Paused)
            {
                MediaPlayer.Resume();
                this.IsUserPaused = false;
                ChangeBtnImg(btn_p,"pause");
            }
            else
            {
                MediaPlayer.Pause();
                this.IsUserPaused = true;
                ChangeBtnImg(btn_p,"play");
            }
        }

        private void btn_n_Click(object sender, EventArgs e)
        {
            PlayListHelper.SongIndex++;
            if (CurrentSong == null)
            {
                ChannelType channel = channelNav.CurrentChannel;
                PlayListHelper.ReFresh(channel);
            }
            else
            {
                this.Play(CurrentSong);
            }
        }

        private void btn_f_Click(object sender, EventArgs e)
        {
            if (this.CurrentSong == null)
                return;

            if (!DbHelper.IsFavSong(this.CurrentSong))
            {
                DbHelper.AddFavSong(this.CurrentSong);
                this.ChangeBtnImg(this.btn_f, "fav");
            }
            else
            {
                DbHelper.DelFavSong(this.CurrentSong);
                this.ChangeBtnImg(this.btn_f, "fav_addto");
            }
        }


        System.Windows.Point pFirst;
        System.Windows.Point pSecond;
        private void AlubmImage_Double_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            pSecond = e.ManipulationOrigin;
            bool IsDo = false;
            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gesture = TouchPanel.ReadGesture();
                //如果是水平手势 起始点的X>结束点的X
                if (gesture.GestureType == GestureType.HorizontalDrag && pFirst.X < pSecond.X&&!IsDo)
                {
                    IsDo = true;
                    this.btn_n_Click(null, null);

                }
            }
    
        }

        private void AlubmImage_Double_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            pFirst = e.ManipulationOrigin;
        }


        
        protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
        {
            MediaPlayer.MediaStateChanged -= new EventHandler<EventArgs>(MediaPlayer_MediaStateChanged);
            PlayListHelper.ReFreshComplete -= new Action(PlayListHelper_ReFreshComplete);
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!NavigationContext.QueryString.Keys.Contains("Channle"))
            {
                channelNav.SetChannel(PlayListHelper.CurrentChannel.ToString());
                this.Restore();
                return;
            }

            string ch = NavigationContext.QueryString["Channle"].ToString();
            var chn = this.GetChannelType(ch);
            this.channelNav.SetChannel(ch);
            if (PlayListHelper.CurrentChannel == chn)
            {
                this.Restore();
                return;
            }
            _CurrentChannel = chn;
            PlayListHelper.ReFresh(_CurrentChannel);
        }

        /// <summary>
        /// 还原
        /// </summary>
        private void Restore()
        {
            this.RePlay(CurrentSong);
            this.IsUserPaused = false;
            ChangeBtnImg(this.btn_p, "pause");
        }
        /// <summary>
        /// 回到播放状态 当时不重新播放歌曲
        /// </summary>
        /// <param name="song"></param>
        private void RePlay(dbSong song)
        {
            if (song == null)
            {
                this.SongName.Text = "No Song！";
                this.AlubmImage.Source = null;
                this.AlubmImage_Copy.Source = null;
                this.SongNameMarquee();
                return;
            }
            if (DbHelper.IsFavSong(song))
            {
                this.ChangeBtnImg(this.btn_f, "fav");
            }
            else
            {
                this.ChangeBtnImg(this.btn_f, "fav_addto");
            }
            Song s = Song.FromUri(song.title, new Uri(song.url));
            this.SongName.Text = song.artist + "-" + song.title;
            this.AlubmImage.Source = new BitmapImage(new Uri(song.picture, UriKind.Absolute));
            this.AlubmImage_Copy.Source = this.AlubmImage.Source;
            this.AlubmImage.Opacity = 0;
            this.AlubmImage_Copy.Opacity = 0;
            this.SongNameMarquee();
            _timer.Start();
        }

        /// <summary>
        /// 后退事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = true;
            this.TranToChannelTile();
            //NavigationService.GoBack();
        }

        private void men_about_Click(object sender, EventArgs e)
        {
            MessageBox.Show("豆瓣电台 for WP7\n作者:kklldog\nQQ:17014842\n免责声明：本软件为个人学习所用，" +
                            "不做任何商业用途！系统中部分图片来自互联网，如本软件的下载者复制分发销售获利都跟" +
                            "作者无关！\nLicense: GNU General Public License v 2", "关于", MessageBoxButton.OK);
        }
    }
}